var uploadImage = require('../../utils/uploadImg/uploadImg');
const {
  getYearMateTime
} = require('../../utils/time')
Component({

  properties: {
    value: {
      type: String,
      observer: function (newVal, oldVal, changePath) {

        var split = []
        if (newVal.indexOf(',') > 0) {
          split = newVal.split(',')
        } else if (newVal) {
          split.push(newVal)
        }


        let temp = []
        split.forEach(url => {
          temp.push({
            url: url
          })
        })
        this.setData({
          files: temp
        })
      }
    },
    edit: {
      type: Boolean,
      value: true // false
    },
    title: {
      type: String,
      value: '图片上传'
    }

  },

  lifetimes: {
    attached() {
      this.setData({
        selectFile: this.selectFile.bind(this),
        uplaodFile: this.uplaodFile.bind(this)
      })



    },
    ready: function () {
      // const query = wx.createSelectorQuery();
      // this.setData({
      //   canvas:query
      // })
      this.initCanvas()
    }
  },


  data: {
    files: [],
    windowWidth: wx.getSystemInfoSync().windowWidth,
    canvasWidthValue: 300,
    canvasHeightValue: 300,
    canvas: null,
    width: null,
    height: null,
    context: null
  },

  observers: {
    'files'(files) {
      this.change(files)
    }
  },

  methods: {

    initCanvas() {
      const that = this;
      const query = wx.createSelectorQuery().in(this)
      query.select('#mycanvas')
        .fields({
          node: true,
          size: true
        })
        .exec((rect) => {
          const canvas = rect[0].node
          let width = rect[0].width;
          let height = rect[0].height;
          that.setData({
            width,
            height,
            canvas
          });

          const context = wx.createCanvasContext('mycanvas', that)
        
          that.setData({
            context: context
          })
          context.setStrokeStyle('#061A06')
          context.setLineWidth(2)
          context.draw()
        })
    },

    change(files) {
      var temp = ''
      files.map((x, y) => {
        temp += y == files.length - 1 ? x.url : (x.url + ',')
      })
      this.triggerEvent('change', temp)

    },

    previewImage: function (e) {
      wx.previewImage({
        current: e.currentTarget.id,
        urls: this.data.files
      })
    },
    selectFile(files) {

    },
    uplaodFile(files) {


      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve('some error')
        }, 1000)
      })
    },
    uploadError(e) {

    },
    uploadSuccess(e) {

    },

    delete(e) {
      const {
        index
      } = e.detail
      let files = this.data.files
      files.splice(index, 1)
      this.setData({
        files: files
      })
    },

    select(e) {
      console.log(e);
      let res = e.detail;
      let that = this
      let prolist = wx.getStorageSync('prolist') == '' ? wx.getStorageSync('prolist') : JSON.parse(wx.getStorageSync('prolist'))
      let time = new Date().getTime()
      const currentTime = getYearMateTime(time);
      const currentLocation = prolist.userName;

      for (var i = 0; i < res.tempFilePaths.length; i++) {

        wx.showLoading({
          title: '上传中' + (i + 1) + '/' + res.tempFilePaths.length,
          mask: true
        })
       
        that.getImage(res.tempFilePaths[i], currentTime, currentLocation)




      }

    },

    getImage(e, currentTime, currentLocation) {
      let that = this
      wx.getImageInfo({
        src: e,
        success(file) {

          that.setData({
            canvasWidthValue: file.width,
            canvasHeightValue: file.height,
          })

          // 这里才能成功获取到 canvas 上下文对象
          let {
            canvas
          } = that.data;

          // console.log(canvas);
          const ctx = canvas.getContext('2d');

          const img = canvas.createImage()
          img.src = file.path
          img.onload = function () {
            //设置画布到校绘制原图到canvas中 
            ctx.canvas.width = file.width / 2
            ctx.canvas.height = file.height / 2
            ctx.drawImage(img, 0, 0, file.width / 2, file.height / 2)

            // 设置水印字体大小、颜色和位置 
            ctx.font = "20px arial";
            ctx.fillStyle = "rgba(255, 252, 153, 0.5)";
            ctx.textAlign = "left";
            ctx.textBaseline = "bottom";
            // 绘制时间和位置信息到canvas中  
            ctx.fillText(currentTime, 10, 30);
            that.drawText(ctx, currentLocation, 10, 60, 232, that.data.windowWidth / 6 * 5) // 自动换行
            setTimeout(() => {
              // 将canvas转换成图片，并将其添加到文件对象中
              wx.canvasToTempFilePath({
                canvas: canvas,
                success: (res) => {
                  console.log(res.tempFilePath);

                  uploadImage(res.tempFilePath, 'upload/',
                    function (result) {

                      wx.hideLoading()
                      var {
                        files
                      } = that.data
                      files.push({
                        url: result
                      })
                      that.setData({
                        files: files
                      })



                    },
                    function (result) {

                      wx.hideLoading()
                      wx.showToast({
                        title: `上传失败,原因${result}`,
                        icon: 'none',
                        duration: 1500,
                        mask: true
                      })

                    }
                  )



                  // 上传包含水印的图片

                },
                fail(res) {
                  console.error('失败', res)
                }
              });
            }, 1000);
          }





        }
      })
    },




    //canvas文本过长 自动换行
    drawText: function (ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
      console.log("woaini", canvasWidth)
      var lineWidth = 0;
      var lastSubStrIndex = 0; //每次开始截取的字符串的索引
      for (let i = 0; i < str.length; i++) {
        lineWidth += ctx.measureText(str[i]).width;
        if (lineWidth > canvasWidth) {
          ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分
          initHeight += 16; //16为字体的高度
          lineWidth = 0;
          lastSubStrIndex = i;
          titleHeight += 30;
        }
        if (i == str.length - 1) { //绘制剩余部分
          ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
        }
      }
      // 标题border-bottom 线距顶部距离
      titleHeight = titleHeight + 10;
      return titleHeight
    },



  }
})